package com.bwie.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.MenuMapper;
import com.bwie.pojo.Menu;
import com.bwie.utils.JwtsUtils;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;

import javax.servlet.http.HttpServletRequest;

/**
* @author :Beyond🎸🎸
* @date : 2025-10-16 08:48:44
* @description
* ${description}
**/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R firstTestRun(User user) {

        return R.OK();
    }

    @Override
    public R login(User user) {

        User one = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName, user.getUserName()));

        if(ObjectUtils.isEmpty(one)){
            return R.ERROR(404,"该用户不存在");
        }

        if(!one.getUserPwd().equals(MD5Utils.encrypt(user.getUserPwd()))){
            return R.ERROR(500,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie")
                .claim("userId", one.getUserId())
                .claim("userPhone", one.getUserPhone())
                .compact();

        redisTemplate.opsForValue().set("token-"+one.getUserId(),token,15, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("user-"+one.getUserId(), JSON.toJSONString(one),15,TimeUnit.MINUTES);
        one.setToken(token);

        HashMap<String, Object> map = new HashMap<>();

        map.put("token",token);
        map.put("user",JSON.toJSONString(one));
        return R.OK(map);

    }

    @Override
    public R getMenuByUserId() {

        String token = request.getHeader("token");

        Integer userId = JwtsUtils.getUserIdByToken(token);



        List<Menu> menuList = menuMapper.getMenuByUserId(userId);

        List<Tree<String>> treeList = TreeUtil.build(menuList, "0", (menu, tree) -> {
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid().toString());
            tree.putExtra("path", menu.getMenuPath());
            tree.setId(menu.getMenuId().toString());
        });

        return R.OK(treeList);
    }

    @Override
    public User getUserNameToSave(Integer id) {

        User user = userMapper.selectById(id);

        return user;
    }
}
